package gorm.springboot.demo.controllers


import gorm.springboot.demo.model.Blog
import gorm.springboot.demo.model.BlogTag
import gorm.springboot.demo.services.BlogService
import gorm.springboot.demo.services.PersonService
import groovy.util.logging.Slf4j
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.transaction.annotation.Transactional
import org.springframework.web.bind.annotation.*

@RestController()
@RequestMapping("/blog")
@Slf4j
@Transactional
class BlogController {
    @Autowired
    BlogService blogService
    @Autowired
    PersonService personService
    /**
     * Blog 列表
     * @return
     */
    @GetMapping(value = "/blogList")
    def blogList() {
        def data = blogService.findAll()
        for (Blog blog in data) {
            println("id:" + blog.id)
            println("title:" + blog.getTitle())
            println("content:" + blog.getContent())
            println("person:" + blog.getPerson().firstName)
        }


        return [msg: "success", size: data.size()]

    }

    /**
     * 查询单个blog
     * @param id
     * @return
     */
    @GetMapping(value = "/blog/{id}")
    def getBlogById(@PathVariable("id") Long id) {
        return [msg: "success", data: blogService.findById(id)]

    }

    /**
     * 添加一个BLog
     * @param title
     * @param content
     * @return
     */
    @PutMapping(value = "/addBlog")
    def addBlog(@RequestBody Map body) {
        def title = body.get("title") as String
        def content = body.get("content") as String
        def personId = body.get("personId") as long

        if (!title || !content || !personId) {
            return ["code": 0, "msg": "参数缺少"]
        }

        def person = personService.findById(personId)
        if (!person) {
            return ["code": 0, "msg": "用户不存在"]
        }
        Blog blog = new Blog(title: title, content: content)
        BlogTag tag0 = new BlogTag(name: "Java", info: "java")
        BlogTag tag1 = new BlogTag(name: "PHP", info: "php")

        blog.setPerson(person)
        blog.addToBlogTagList(tag0)
        blog.addToBlogTagList(tag1)

        blogService.save(blog)
        return [msg: "blog save success"]


    }



}
